<template>
  <div class="register-container">
    <el-form :model="formData" :rules="formRules" ref="registerForm" label-width="80px" class="register-form">
      <el-form-item>
        <h1 class="title">小布的店铺(注册)</h1>
      </el-form-item>
      <el-form-item label="账号" prop="usercode">
        <el-input v-model="formData.usercode"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formData.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRegister">注册</el-button>
        <el-button type="primary" @click="toLgoin">已有账号？</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import userApi from "@/api/user/user_api";
export default {
  data() {
    return {
      formData: {
        phone: '',
        email: '',
        usercode: '',
        password: ''
      },
      formRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {  pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱', trigger: ['blur', 'change'] }
        ],
        usercode: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码至少六个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          userApi.register(this.formData).then(res=>{
            this.$message({
              message: '注册成功',
              type: 'success'
            });
          }).catch(error => {
            console.error(error);
          });
        } else {
          console.log('Validation failed');
          return false;
        }
      });
    },
    toLgoin(){
      this.$router.push('/')
    }
  }
};
</script>

<style>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.register-form {
  width: 400px;
}
</style>
